package drugdealer.data;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

import drugdealer.exception.UserTypeException;
import drugdealer.model.Medicamento;

/**
 * Helper class to manage DB related functions for the "Usuario" class.
 * 
 * @author erico
 *
 */
public class MedicamentoDAO {
	/**
	 * Static method to insert a new medicine into the database.
	 * This method does not check the validity of data in "Medicamento" object
	 * passed as parameter "medicamento".
	 * 
	 * @param medicamento is the medicine to be added.
	 * @return different than 0 if successful, 0 otherwise.
	 * @throws UserTypeException 
	 */
	public static int insert(Medicamento medicamento) throws UserTypeException {
		// Get ConnectionPool
		ConnectionPool pool = ConnectionPool.getInstance();

		// Open DB connection
		Connection connection = pool.getConnection();

		// PreparedStatement contains a query template
		// which can be dynamically populated
		PreparedStatement ps = null;

		// Query templates
		// For MedicamentoDados
		String queryMedicamentoDados = "INSERT INTO MedicamentoDados (Nome, ViaDeUso, Descricao)"
					+ "VALUES (?, ?, ?)";
		
		try {
			int result = 0;
			
			/*****************
			  MedicamentoDados
			 *****************/
			// Populate the query template for MedicamentoDados table
			ps = connection.prepareStatement(queryMedicamentoDados);
			ps.setString(1, medicamento.getNome());
//			ps.setInt(2, medicamento.getQuantidadeEmEstoque());
			ps.setString(2, medicamento.getViaDeUso());
			ps.setString(3, medicamento.getDescricao());
			
			// Insert data into UsuarioDados table
			result += ps.executeUpdate();
			
			return result;
		} catch (SQLException sqle) {
			// todo exceptions throwing
			sqle.printStackTrace();
			return 0;
		} finally {
			pool.freeConnection(connection);
		}
	}
	
	
}
